#include <gflags/gflags.h>
#include <butil/logging.h>
#include <brpc/server.h>
#include "http.pb.h"

DEFINE_int32(port, 8000, "TCP Port of this server");

// 简单的 HTTP 服务实现
namespace example {
class HttpServiceImpl : public HttpService {
public:
    void Echo(google::protobuf::RpcController* cntl_base,
              const HttpRequest*,
              HttpResponse*,
              google::protobuf::Closure* done) {
        brpc::ClosureGuard done_guard(done);
        brpc::Controller* cntl = static_cast<brpc::Controller*>(cntl_base);

        // 设置响应类型为纯文本
        cntl->http_response().set_content_type("text/plain");

        // 返回收到的请求内容
        std::string request_body = "hello, " + cntl->request_attachment().to_string();
        cntl->response_attachment().append(request_body);
    }
};
}  // namespace example

int main(int argc, char* argv[]) {
    GFLAGS_NAMESPACE::ParseCommandLineFlags(&argc, &argv, true);

    brpc::Server server;
    example::HttpServiceImpl http_svc;

    // 添加 HTTP 服务
    if (server.AddService(&http_svc, brpc::SERVER_DOESNT_OWN_SERVICE) != 0) {
        LOG(ERROR) << "Fail to add http_svc";
        return -1;
    }

    // 启动服务器
    if (server.Start(FLAGS_port, NULL) != 0) {
        LOG(ERROR) << "Fail to start HttpServer";
        return -1;
    }

    server.RunUntilAskedToQuit();
    return 0;
}
